headers
is a toolkit for working with HTTP headers in JavaScript.
HTTP headers contain a wealth of information:
- Who is sending this request?
- What's in the payload and how is it encoded?
- What is the filename of this file upload?
- and much more!
The built-in JavaScript Headers
interface accepts and gives you strings for everything, which you're probably used to parsing and stringifying manually as needed. This library aims to give you a more fluent interface for all of this information. Similar to how the DOM gives you programmatic access to HTML documents, headers
gives you access to HTTP headers.
Installation
npm install @mjackson/headers
Overview
import Headers from '@mjackson/headers';
let headers = new Headers();
headers.accept = { 'text/html': 1, 'text/*': 0.9 };
headers.accept.mediaTypes;
Object.fromEntries(headers.accept.entries());
headers.accept.accepts('text/html');
headers.accept.accepts('text/plain');
headers.accept.accepts('image/jpeg');
headers.accept.getPreferred(['text/plain', 'text/html']);
headers.accept.set('text/plain', 0.9);
headers.accept.set('text/*', 0.8);
headers.get('Accept');
headers.acceptEncoding = { gzip: 1, deflate: 0.8 };
headers.acceptEncoding.accepts('gzip');
headers.acceptEncoding.accepts('br');
headers.acceptEncoding.getPreferred(['gzip', 'deflate']);
headers.acceptLanguage = { 'en-US': 1, en: 0.9 };
headers.acceptLanguage.languages;
Object.fromEntries(headers.acceptLanguage.entries());
headers.acceptLanguage.accepts('en');
headers.acceptLanguage.accepts('ja');
headers.acceptLanguage.getPreferred(['en-US', 'en-GB']);
headers.acceptLanguage.getPreferred(['en', 'fr']);
headers.acceptRanges = 'bytes';
headers.connection = 'close';
headers.contentType = 'application/json; charset=utf-8';
headers.contentType.mediaType;
headers.contentType.charset;
headers.contentType.charset = 'iso-8859-1';
headers.get('Content-Type');
headers.contentDisposition =
'attachment; filename="example.pdf"; filename*=UTF-8\'\'%E4%BE%8B%E5%AD%90.pdf';
headers.contentDisposition.type;
headers.contentDisposition.filename;
headers.contentDisposition.filenameSplat;
headers.contentDisposition.preferredFilename;
headers.cookie = 'session_id=abc123; user_id=12345';
headers.cookie.get('session_id');
headers.cookie.get('user_id');
headers.cookie.set('theme', 'dark');
headers.get('Cookie');
headers.host = 'example.com';
headers.lastModified = new Date();
headers.get('Last-Modified');
headers.location = 'https://example.com';
headers.referer = 'https://example.com/';
headers.setCookie = ['session_id=abc123; Path=/; HttpOnly'];
headers.setCookie[0].name;
headers.setCookie[0].value;
headers.setCookie[0].path;
headers.setCookie[0].httpOnly;
headers.setCookie[0].maxAge = 3600;
headers.setCookie[0].secure = true;
headers.get('Set-Cookie');
headers.setCookie.push('user_id=12345; Path=/api; Secure');
for (let cookie of headers.getSetCookie()) {
console.log(cookie);
}
Headers
can be initialized with an object config:
let headers = new Headers({
contentType: {
mediaType: 'text/html',
charset: 'utf-8',
},
setCookie: [
{ name: 'session', value: 'abc', path: '/' },
{ name: 'theme', value: 'dark', expires: new Date('2021-12-31T23:59:59Z') },
],
});
console.log(`${headers}`);
Headers
works just like DOM's Headers
(it's a subclass) so you can use them anywhere you need a Headers
.
import Headers from '@mjackson/headers';
let response = await fetch('https://example.com', {
headers: new Headers(),
});
let headers = new Headers(response.headers);
headers.set('Content-Type', 'text/html');
headers.get('Content-Type');
If you're familiar with using DOM Headers
, everything works as you'd expect.
Headers
are iterable:
let headers = new Headers({
'Content-Type': 'application/json',
'X-API-Key': 'secret-key',
'Accept-Language': 'en-US,en;q=0.9',
});
for (let [name, value] of headers) {
console.log(`${name}: ${value}`);
}
If you're assembling HTTP messages, you can easily convert to a multiline string suitable for using as a Request/Response header block:
let headers = new Headers({
'Content-Type': 'application/json',
'Accept-Language': 'en-US,en;q=0.9',
});
console.log(`${headers}`);
Low-level API
In addition to the high-level Headers
API, headers
also provides a rich set of primitives you can use to work with just about any complex HTTP header value. Each header class includes a spec-compliant parser (the constructor), stringifier (toString
), and getters/setters for all relevant attributes. Classes for headers that contain a list of fields, like Cookie
, are Iterable
.
All individual header classes may be initialized with either a) the string value of the header or b) an init
object specific to that header.
The following headers are currently supported:
If you need support for a header that isn't listed here, please send a PR! The goal is to have first-class support for all common HTTP headers.
Accept
let header = new Accept('text/html;text/*;q=0.9');
header.has('text/html');
header.has('text/plain');
header.accepts('text/html');
header.accepts('text/plain');
header.accepts('text/*');
header.accepts('image/jpeg');
header.getPreferred(['text/html', 'text/plain']);
for (let [mediaType, quality] of header) {
}
let header = new Accept({ 'text/html': 1, 'text/*': 0.9 });
let header = new Accept(['text/html', ['text/*', 0.9]]);
Accept-Encoding
let header = new AcceptEncoding('gzip,deflate;q=0.9');
header.has('gzip');
header.has('br');
header.accepts('gzip');
header.accepts('deflate');
header.accepts('identity');
header.accepts('br');
header.getPreferred(['gzip', 'deflate']);
for (let [encoding, weight] of header) {
}
let header = new AcceptEncoding({ gzip: 1, deflate: 0.9 });
let header = new AcceptEncoding(['gzip', ['deflate', 0.9]]);
Accept-Language
let header = new AcceptLanguage('en-US,en;q=0.9');
header.has('en-US');
header.has('en-GB');
header.accepts('en-US');
header.accepts('en-GB');
header.accepts('en');
header.accepts('fr');
header.getPreferred(['en-US', 'en-GB']);
header.getPreferred(['en', 'fr']);
for (let [language, quality] of header) {
}
let header = new AcceptLanguage({ 'en-US': 1, en: 0.9 });
let header = new AcceptLanguage(['en-US', ['en', 0.9]]);
Cache-Control
import { CacheControl } from '@mjackson/headers';
let header = new CacheControl('public, max-age=3600, s-maxage=3600');
header.public;
header.maxAge;
header.sMaxage;
let header = new CacheControl({ public: true, maxAge: 3600 });
Content-Disposition
import { ContentDisposition } from '@mjackson/headers';
let header = new ContentDisposition('attachment; name=file1; filename=file1.txt');
header.type;
header.name;
header.filename;
header.preferredFilename;
let header = new ContentDisposition({
type: 'attachment',
name: 'file1',
filename: 'file1.txt',
});
Content-Type
import { ContentType } from '@mjackson/headers';
let header = new ContentType('text/html; charset=utf-8');
header.mediaType;
header.boundary;
header.charset;
let header = new ContentType({
mediaType: 'multipart/form-data',
boundary: '------WebKitFormBoundary12345',
charset: 'utf-8',
});
Cookie
import { Cookie } from '@mjackson/headers';
let header = new Cookie('theme=dark; session_id=123');
header.get('theme');
header.set('theme', 'light');
header.delete('theme');
header.has('session_id');
for (let [name, value] of header) {
}
let header = new Cookie({ theme: 'dark', session_id: '123' });
let header = new Cookie([
['theme', 'dark'],
['session_id', '123'],
]);
Set-Cookie
import { SetCookie } from '@mjackson/headers';
let header = new SetCookie('session_id=abc; Domain=example.com; Path=/; Secure; HttpOnly');
header.name;
header.value;
header.domain;
header.path;
header.secure;
header.httpOnly;
header.sameSite;
header.maxAge;
header.expires;
let header = new SetCookie({
name: 'session_id',
value: 'abc',
domain: 'example.com',
path: '/',
secure: true,
httpOnly: true,
});
License
See LICENSE